package com.sikaryofficial.backend.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.sikaryofficial.backend.domain.dto.resp.productactivity.ActivityDTO;
import com.sikaryofficial.backend.domain.entity.ActivityResult;
import com.sikaryofficial.backend.domain.vo.UserMonthlyWinVO;
import com.sikaryofficial.backend.mapper.ActivityResultMapper;
import com.sikaryofficial.backend.service.IActivityResultService;
import com.sikaryofficial.common.security.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 活动结果Service业务层处理
 *
 * @author qinjinyuan
 * @date 2023-11-02
 */
@Service
public class ActivityResultServiceImpl extends ServiceImpl<ActivityResultMapper, ActivityResult> implements IActivityResultService {
    @Autowired
    private ActivityResultMapper activityResultMapper;

    /**
     * 查询用户对应活动的结果记录
     *
     * @param activityIds
     * @return
     */
    @Override
    public Map<Long, ActivityResult> getAttendResult(List<Long> activityIds) {
        if (CollUtil.isEmpty(activityIds)) {
            return Maps.newHashMap();
        }
        // 查询参与结果数据
        List<ActivityResult> activityResults = this.list(new LambdaQueryWrapper<ActivityResult>()
                .in(ActivityResult::getActivityId, activityIds)
                .eq(ActivityResult::getDeletedVersion, 0L)
                .eq(ActivityResult::getCreatedBy, SecurityUtils.getUserId())
        );
        return activityResults.stream().collect(Collectors.toMap(ActivityResult::getActivityId, Function.identity(), (k1, k2) -> k1));
    }

    /**
     * 根据活动ID，获取抢购结果数量
     *
     * @param activityIds
     * @return
     */
    @Override
    public Map<Long, Integer> getPurchaseCountList(List<Long> activityIds) {
        if (CollUtil.isEmpty(activityIds)) {
            return Maps.newHashMap();
        }
        Map<Long, Integer> resultMap = Maps.newHashMap();
        List<ActivityDTO> resultList = activityResultMapper.getPurchaseCountList(activityIds);
        for (ActivityDTO item : resultList) {
            resultMap.put(item.getActivityId(), item.getPurchaseNum());
        }
        return resultMap;
    }

    /**
     * 获取用户月度中奖列表
     *
     * @return
     */
    @Override
    public List<UserMonthlyWinVO> getUserMonthlyWinList() {
        return activityResultMapper.getUserMonthlyWinList();
    }
}
